#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import re
import os
import sys
from optparse import OptionParser

from config import Config
from cluster import Cluster
from utils import _exec_remote

config = Config()
cluster = Cluster()

def nohosts():
    return config.nohosts

def rhostname(hostip, hostname):
    '''在集群中任何一个节点上修改/opt/fusionstack/etc/hosts.conf，
    完成后执行lich update etc，同步到集群内所有节点上，
    然后重启集群，即可完成'''
    print 'rehostname', hostip, hostname

def _change_clusterconf(old, new, origins = None):
    #todo 得到原有所有的ip， 如果当前文件中有无效的，删除
    ftxt = config.clusterconf
    result = []
    with open(ftxt, "r") as f:
        for l in f:
            if old == l.strip():
                l = "%s\n" % (new)
            result.append(l)

    with open(ftxt, "w") as f:
        f.write("".join(result))

def _change_hosts(old, new, origins = None):
    #todo 得到原有所有的ip， 如果当前文件中有无效的，删除
    ftxt = config.hosts_conf
    result = []
    with open(ftxt, "r") as f:
        for l in f:
            _l = l.strip()
            if _l:
                ls = _l.split()
                if old == ls[0]:
                    ls[0] = new
                    l = "%s\n" % (" ".join(ls))

            result.append(l)

    with open(ftxt, "w") as f:
        f.write("".join(result))

def _change_name(old, new):
    cmd = """
        pre=`lich configdump|grep globals.home|awk -F":" '{print $2}'`;
        for i in `ls ${pre}/disk/`;
        do
            file=/opt/fusionstack/disk/${i}/node/config/name;
            sed -i s#^%s\/#%s\/#g ${file};
        done""" % (old, new)
    _exec_remote(new, cmd)

def _change_quorum(hosts, old, new):
    cmd = """
        pre=`lich configdump|grep globals.home|awk -F":" '{print $2}'`;
        for i in `ls ${pre}/disk/`;
        do
            file=${pre}/disk/${i}/node/paxos/quorum;
            sed -i s#^%s\/#%s\/#g ${file};
        done""" % (old, new)
    for h in hosts:
        _exec_remote(h, cmd)

def _change_rootable(hosts, old, new):
    cmd = """
        old=%s;
        new=%s;
        pre=`lich configdump|grep globals.home|awk -F":" '{print $2}'`;
        for i in `ls ${pre}/disk/`;
        do
            for j in `ls ${pre}/disk/${i}/node/rootable/disk/`;
                do 
                    ip=`echo $j|awk -F":" '{print $1}'`;
                    id=`echo $j|awk -F":" '{print $2}'`;
                    #echo $ip, $id;
                    if [ $ip == $old ];
                    then
                        oldfile="${pre}/disk/${i}/node/rootable/disk/${ip}:${id}"
                        newfile="${pre}/disk/${i}/node/rootable/disk/${new}:${id}"
                        #echo "==", ${oldfile}, ${newfile};
                        mv ${oldfile} ${newfile};
                    fi;
                done;
        done""" % (old, new)
    for h in hosts:
        _exec_remote(h, cmd)

def _clean_shm(hosts):
    cmd = "rm -rf /dev/shm/lich4/"
    for h in hosts:
        _exec_remote(h, cmd)

def _clean_acceptor(hosts):
    cmd = """
        pre=`lich configdump|grep globals.home|awk -F":" '{print $2}'`;
        for i in `ls ${pre}/disk/`;
        do
            acceptor=${pre}/disk/${i}/node/paxos/acceptor;
            rm -rf $acceptor;
        done"""

    for h in hosts:
        _exec_remote(h, cmd)

def rhostip(ip, ipnew):
    _change_clusterconf(ip, ipnew)
    _change_hosts(ip, ipnew)

    cluster.config.hosts_load()
    hosts = cluster.config.hosts.keys()
    cluster.update('etc')

    _change_name(ip, ipnew)
    _change_quorum(hosts, ip, ipnew)
    #_change_rootable(hosts, ip, ipnew)
    _clean_shm(hosts)
    _clean_acceptor(hosts)

def usage():
    print >>sys.stderr, "usage:"
    print >>sys.stderr, sys.argv[0] + " --ip <ip> --ipnew <ipnew>"

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("--ip", dest="ip", type='string', help="hostip")
    parser.add_option("--ipnew", dest="ipnew", type='string', help="hostip")

    (options, args) = parser.parse_args()
    #print options, args

    if not nohosts():
        print >>sys.stderr, "error, this tool just run with nohosts"
        sys.exit(1)

    ip = options.ip
    ipnew = options.ipnew
    if not all([ip, ipnew]):
        usage()
        sys.exit(1)

    rhostip(ip, ipnew)
